# -*- coding: utf-8 -*-
import web
from model import db
from hashlib import md5
from web.contrib.template import render_jinja

render = render_jinja(
	 'templates/main', 
	 encoding = 'utf-8',
	)

class dologin:
	def GET(self):
    	 	raise web.seeother('/')

	def POST(self):
	 	input = web.input(username=None, passwd=None, role=None)
		if input.username is not None and input.passwd is not None and input.role is not None:
	 	 	role = input.role
	    		username = input.username
	    		passwd = input.passwd
		else:
	 	 	#invaild input
		    	return render.index(auth_fail_code=3)

	 	try:
			 user = db.select(role, {"username":username}, where="username=$username")[0]
		except Exception, e:
			 #there isn`t username ,code 2
		    	 return render.index(auth_fail_code=1)
		
		if user is not None:
			hash = md5()
	    		hash.update(passwd)
	    		if user["passwd"] == hash.hexdigest():
				 #login ok
				 #insert userinfo into session
				 web.ctx.session.user = username
	 	 	 	 return web.ctx.session.user
	    		else:	 
		     		 #username or passwd error ,code 1
		    		 return render.index(auth_fail_code=1)
	 	else:
			 #there isn`t username ,code 2
		    	 return render.index(auth_fail_code=2)
